define(["jquery", "easy-admin"], function ($, ea) {

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTableRenderId',
        index_url: 'admin/miniapp/module/index',
        add_url: 'admin/miniapp/module/add',
        edit_url: 'admin/miniapp/module/edit',
        delete_url: 'admin/miniapp/module/del',
        export_url: 'admin/miniapp/module/export',
        modify_url: 'admin/miniapp/module/modify',
        role_url: 'admin/miniapp/module/group',
    };
    var form = layui.form;
    var tree = layui.tree;
    var laytpl = layui.laytpl;
    var Controller = {

        index: function () {
            ea.table.render({
                init: init,
                toolbar: ['refresh', 'delete','add'],
                cols: [[
                    {type: 'checkbox'},
                    {field: 'id', title: 'id'},
                    {field: 'miniapp_id', title: '应用id', search: false},
                    {field: 'group_id', title: '套餐功能组id', search: false},
                    {field: 'name', title: '套餐名', search: false},
                    // {field: 'type', search: 'select', selectList: {"1": "基础功能", "2": "附加功能", "3": "插件功能"}, title: '类型'},
                    // {field: 'price', title: '价格', search: false},
                    // {field: 'valid_days', title: '有效天数',templet:function (data) {
                    //     if(data.type == 1){
                    //         if(data.valid_days == 0)return '永久';
                    //         return data.valid_days + '天';
                    //     }else{
                    //         return '无';
                    //     }
                    //     }, search: false},
                    {field: 'desc', title: '描述', search: false},
                    {field: 'create_time', title: '创建时间', templet: ea.table.date, width: 180, search: false},
                    {width: 250, title: '操作', templet: ea.table.tool},
                ]],
            });

            ea.listen();
        },
        add: function () {
            module.init();
            module.priceListen();
            module.priceValueListen();
            ea.listen();
        },
        edit: function () {
            module.init();
            module.priceListen();
            module.priceValueListen();
            ea.listen();
        },
    };


    var module = {
        data:{
            tree_id:'roles',
            price_json:price_json,
        },
        param:{
            id:id,
            miniapp_id:miniapp_id,
        },
        init: function () {
            form.on('radio(type)', function (data) {
                module.listenType(data.value)
            });
            //初始化角色选择组
            this.role_init();
        },
        listenType: function (display) {
            if (!display) display = $("input[name='type']:checked").val();
            switch (display) {
                case '1': //隐藏
                    $("#valid_days").show();
                    break;
                default: //显示
                    $("#valid_days").hide();
                    $("input[name='days']").val(0);
                    break;
            }
        },
        role_init:function () {
         this.setRoleList();
        },
        setRoleList: function () {
            var _this = this;
            ea.request.get({
                url: '/' + CONFIG.ADMIN + '/' + init.role_url + '?'+ $.param(_this.param),
            }, function (res) {
                _this.setRole(res.data.data);//插件列表渲染
            }, function (res) {
                ea.msg.error(res.msg); //失败
            }, function (that) {
                ea.msg.error('查询失败');//异常
            });
        },
        setRole:function (data) {
            var _this = this;
            console.log(_this.data.tree_id);
            //开启复选框
            tree.render({
                elem: '#roles'
                ,data: data
                ,id: _this.data.tree_id //定义索引
                ,showCheckbox: true
                ,oncheck: function(obj){
                    try{
                        //获得选中的节点
                        var checkData = _this.getTreeIds(tree.getChecked(_this.data.tree_id),[]);
                        $('#group_id').val(checkData.join(','));
                    }catch (e) {
                        //初始化时getChecked尚未挂载，捕获并抛警告
                        console.warn(e.message);
                    }
                }
            });
        },
        getTreeIds:function (treeNode, result) { //递归得到树中所有id
        for (var i in treeNode) {
            result.push(treeNode[i].id);
            result = this.getTreeIds(treeNode[i].children, result);
        }
        return result;
       },
        priceListen:function () {
            this.init_price();
            this.add_price_listen();
            this.delete_price_listen();
            // this.priceListen();
        },
        add_price_listen:function(){
            var _this = this;
            $("#add_price").click(function () {
                //渲染空数据
                var data = {
                    title:'',
                    day:'',
                    price:'',
                };
                _this.renderPrice([data]);
                _this.getPrice();
            });
        },
        delete_price_listen:function(){
            var _this = this;
            $("body").on("click",".delete-price",function(){
                var pricelist = _this.getPrice();
                if(pricelist.length >1){
                    $(this).parent().remove();
                }else{
                    ea.msg.error('最后一个价格不能删除！');//异常
                }
            })
        },
        init_price:function (){
            //初始化
            if(!this.data.price_json.length){
                //渲染空数据
                var data = {
                    title:'',
                    day:'',
                    price:'',
                };
                this.renderPrice([data]);
            }else{
                this.renderPrice(this.data.price_json);
            }
            this.getPrice();
        },
        renderPrice:function (data) {
            //生成价格套餐
            //渲染插件
            var getTpl = price_template.innerHTML;
            laytpl(getTpl).render(data, function (html) {
                $("#set_price").append(html);
            });
        },
        getPrice:function () {
            var  title=$('input[name="title[]"').map(function(){ return $(this).val(); }).get();
            var day=$('input[name="day[]"').map(function(){ return $(this).val(); }).get();
            var price=$('input[name="price[]"').map(function(){ return $(this).val(); }).get();
            var weight=$('input[name="weight[]"').map(function(){ return $(this).val(); }).get();
            var arr=new Array();
            for (var i=0;i<title.length;i++)
            {
                var arr2={};
                    arr2['title'] =title[i];
                    arr2['day'] =day[i]?day[i]:0;
                    arr2['price'] =price[i]?price[i]:0;
                    arr2['weight'] =weight[i];
                // 规格标识为： 天数 + 价格 + 混淆值
                    var encode = encodeURI(arr2['day'] + arr2['price'] + 'bwsaas');
                    arr2['id'] = btoa(encode);
                    arr.push(arr2);
            }
            $('#price_json').val(JSON.stringify(arr));
            return arr;
        },
        priceValueListen:function () {
            var _this = this;
            $("body").on("change",".price-change",function(){
               _this.getPrice();
            });
        }

    }
    return Controller;
});